package com.ifonly.handler;

import com.google.common.base.Strings;
import com.ifonly.render.RenderException;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-10 13:02
 * @since JDK 1.6
 */
public abstract class Handler {

    protected Handler next;

    public abstract void handle(String target, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled);

    protected void redirect(String url, HttpServletRequest request, HttpServletResponse response, boolean[] isHandled) {
        isHandled[0] = true;

        String queryString = request.getQueryString();
        if (queryString != null)
            url = url + "?" + queryString;

        String contextPath = request.getContextPath();
        if (!Strings.isNullOrEmpty(contextPath) && !"/".equals(contextPath)) {
            url = contextPath + url;
        }

        try {
            response.sendRedirect(url);    // always 302
        } catch (IOException e) {
            throw new RenderException(e);
        }
    }

}
